import 'dart:async';
import 'dart:convert';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rider/event/back_map_pop_car_event.dart';
import 'package:flutter_rider/event/show_pop_select_car_event.dart';
import 'package:flutter_rider/event/click_stations_event.dart';
import 'package:flutter_rider/main/widgets/dialog/alert_dialog.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/pop/pop_car_list.dart';
import 'package:flutter_rider/main/widgets/pop/pop_car_status.dart';
import 'package:flutter_rider/main/widgets/pop/pop_stations.dart';
import 'package:flutter_rider/main/widgets/state/state_layout.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/kit/cluster_kit.dart';
import 'package:flutter_rider/main/models/station_model.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_svg/svg.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_rider/config.dart';
import 'package:flutter_rider/event/logout_event.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/utils/log.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/utils/extension.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:flutter_rider/module/login/page/login_page.dart';

import '../../../event/change_stations_event.dart';

class HomePage extends StatefulWidget {

  HomePage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return HomePageState();
  }
}

class HomePageState extends State<HomePage> with WidgetsBindingObserver {
  dynamic _data;
  dynamic _datCache;
  dynamic _temporaryData;
  AMapController? _mapController;
  final Map<String, Marker> _markers = <String, Marker>{};
  final Map<String, Polyline> _polylines = <String, Polyline>{};
  var _isLoading = false;
  final StateLayoutController _stateLayoutController = StateLayoutController();
  late StreamSubscription _eventFn1;
  late StreamSubscription _eventFn2;
  Timer? _refreshTimer;
  bool _hasShowNoLogin = false;
  bool _hasOkLoad = false;
  double _curZoom = 16.0;
  bool _isPageShow = true;
  var _stationMd5 = "";
  List _cacheStations = [];
  int _status = 0;
  bool _isAll = true;
  bool _isDidpatch = false;
  bool _isWork = false;
  bool _isWait = false;
  bool _isBroke = false;
  int all_count = 0;
  String _car_no = "";
  bool useStationCache = false;
  dynamic beforeActiveStation;
  dynamic currenActiveStation;


  //被选中的车
  late Cluster _selectElement;
  late StreamSubscription _backMapPopCarEvent;

  late StreamSubscription _clickMapPopCarEvent;
  //是否正在操作选车调车
  bool _isShowPopSelectCar = false;

  @override
  Widget build(BuildContext context) {
    return Material(
        child: StateLayout(
      url: "/home/index?station_md5=$_stationMd5",
      controller: _stateLayoutController,
      dataCallback: _onDataCallback,
      childBuilder: _renderContent,
      errorCallback: (_, __) {
        setState(() {
          _isLoading = false;
        });
      },
    ));
  }

  @override
  void initState() {
    super.initState();

    _clickMapPopCarEvent = eventBus.on<ShowPopSelectCarEvent>().listen((event) {
      _isShowPopSelectCar = event.isShowPopSelectCar;
    });

    _backMapPopCarEvent = eventBus.on<BackMapPopCarEvent>().listen((event) {
      _popCarClick(_selectElement);
    });

    _eventFn1 = eventBus.on<LogoutEvent>().listen((event) {
      if (!_hasShowNoLogin) {
        _hasShowNoLogin = true;

        CustomAlertDialog.alert(context, content: "您的账号在其他设备登录，已被迫下线。",
            onConfirm: () {
          Navigator.pushAndRemoveUntil(context,
              MaterialPageRoute(builder: (context) {
            return LoginPage();
          }), (route) => false);
        });
      }
    });

    _eventFn2 = eventBus.on<ChangeStationsEvent>().listen((event) {
      renderStation3();
    });

    if (kReleaseMode) {//只有release才刷新
      _refreshTimer = Timer.periodic(const Duration(seconds: 5), (timer) {
        if (mounted &&
            _hasOkLoad &&
            _isPageShow &&
            !_isLoading &&
            ModalRoute.of(context)?.isCurrent == true) {
          setState(() {
            _isLoading = true;
          });
          _stateLayoutController.reload();
        }
      });
    }
    WidgetsBinding.instance?.addObserver(this);
  }

  @override
  void dispose() {
    super.dispose();
    _eventFn1.cancel();
    _eventFn2.cancel();
    _refreshTimer?.cancel();
    _mapController?.disponse();
    WidgetsBinding.instance?.removeObserver(this);
    Log.i("dispose...");
    _clickMapPopCarEvent.cancel();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.resumed:
        Log.i("resumed");
        _isPageShow = true;
        break;
      case AppLifecycleState.inactive:
        Log.i("inactive");
        _isPageShow = false;
        break;
      case AppLifecycleState.paused:
        Log.i("paused");
        break;
      case AppLifecycleState.detached:
        Log.i("detached");
        break;
    }
  }

  _onDataCallback(dynamic data) async {
    _data = data;
    _hasOkLoad = true;

    /// 根据选择的车辆状态筛选符合条件的车辆
    filterCar();

    /// 渲染站点
    renderStation();

    /// 绘画连接线
    _renderLine();

    /// 渲染车辆
    calcCluster();
  }

  /// 根据选择的车辆状态筛选符合条件的车辆
  filterCar() async {
    all_count = 0;
    // 计算总共多少辆车
    _data["satistics_info"].forEach((value, key) => {all_count += key as int});
    if (_status == -1 || _status == 2 || _status == 3 || _status == 4) {
      List list = [];
      List carList = List.from(_data["car_list"]);
      for (var item in carList) {
        if (_isAll ||
            item["status"] == 4 && _isDidpatch ||
            item["status"] == 3 && _isWork ||
            item["status"] == 2 && _isWait ||
            item["status"] == -1 && _isBroke) {
          list.add(item);
        }
      }
      _temporaryData = _data;
      _temporaryData["car_list"] = list;
      _data = _temporaryData;
    } else {
      var _sp = await SharedPreferences.getInstance();
      _sp.setString("dataCache", jsonEncode(_data));
    }
  }

  /// 渲染站点
  renderStation() {
    var stations;
    bool useStationCache = false;
    /// 当无新站点，不重新渲染站点
    if (_stationMd5.compareTo(_data["station_md5"]) == 0) {
      stations = [];
      useStationCache = true;
    } else {
      _cacheStations = _data["station_list"];
      stations = _data["station_list"];
      _stationMd5 = _data["station_md5"];
    }

    Map<String, Marker> tmpMarkers = {};
    if (!useStationCache && stations != null) {
      // 显示站点
      for (var element in stations) {
        tmpMarkers["s_${element["id"]}"] = Marker(
            zIndex: 1,
            position:
                LatLng(toDouble(element["lat"]), toDouble(element["lng"])),
            icon: BitmapDescriptor.fromIconPath(R.image_poi_station), //R.image_poi_map_reconnaissance
            infoWindow: InfoWindow(
                title: element["station_name"],
                snippet: "${element["lat"]}, ${element["lng"]}"),
            infoWindowEnable: false,
            onTap: (e) {
              _popStationClick(element);
            });
      }
    }

    if (!useStationCache) {
      _markers.removeWhere((key, value) => key.startsWith("s_"));
    }
    setState(() {
    _markers.addAll(tmpMarkers);
    });
    // 我的位置加载图标
    _isLoading = false;
  }

  /// 渲染站点2
  renderStation2() {
    Map<String, Marker> tmpMarkers = {};
        if(beforeActiveStation !=null) {
          Map clonedObject = jsonDecode(jsonEncode(beforeActiveStation));
          tmpMarkers["s_${clonedObject["id"]}"] = Marker(
              zIndex: 1,
              position:
              LatLng(toDouble(clonedObject["lat"]), toDouble(clonedObject["lng"])),
              icon: BitmapDescriptor.fromIconPath(R.image_poi_station), //R.image_poi_map_reconnaissance
              infoWindow: InfoWindow(
                  title: clonedObject["station_name"],
                  snippet: "${clonedObject["lat"]}, ${clonedObject["lng"]}"
              ),
              infoWindowEnable: false,
              onTap: (e) {
                _popStationClick(clonedObject);
              }
          );
          _markers.removeWhere((key, value) => key.startsWith("s_${clonedObject["id"]}"));
          setState(() {
            _markers.addAll(tmpMarkers);
          });
        }
        tmpMarkers["s_${currenActiveStation["id"]}"] = Marker(
            zIndex: 1,
            position:
            LatLng(toDouble(currenActiveStation["lat"]), toDouble(currenActiveStation["lng"])),
            icon: BitmapDescriptor.fromIconPath(R.image_component), //R.image_poi_map_reconnaissance
            infoWindow: InfoWindow(
                title: currenActiveStation["station_name"],
                snippet: "${currenActiveStation["lat"]}, ${currenActiveStation["lng"]}"),
            infoWindowEnable: false,
            onTap: (e) {
              _popStationClick(currenActiveStation);
            }
        );

        _markers.removeWhere((key, value) => key.startsWith("s_${currenActiveStation["id"]}"));
        setState(() {
          _markers.addAll(tmpMarkers);
        });
        beforeActiveStation = currenActiveStation;
  }

  /// 渲染站点3
  renderStation3() {
    Map<String, Marker> tmpMarkers = {};
      tmpMarkers["s_${currenActiveStation["id"]}"] = Marker(
          zIndex: 1,
          position:
          LatLng(toDouble(currenActiveStation["lat"]), toDouble(currenActiveStation["lng"])),
          icon: BitmapDescriptor.fromIconPath(R.image_poi_station), //R.image_poi_map_reconnaissance
          infoWindow: InfoWindow(
              title: currenActiveStation["station_name"],
              snippet: "${currenActiveStation["lat"]}, ${currenActiveStation["lng"]}"
          ),
          infoWindowEnable: false,
          onTap: (e) {
            _popStationClick(currenActiveStation);
          }
      );
      _markers.removeWhere((key, value) => key.startsWith("s_${currenActiveStation["id"]}"));
      setState(() {
        _markers.addAll(tmpMarkers);
      });
  }

  /// 绘画连接线
  _renderLine() {
    Map<String, Polyline> tmpPolylines = {};
    // 有目的地的时候，从车辆到目的地画一条线
    var cars = _data["car_list"];
    for (var element in cars) {
      // 目的地
      var dest = element["destination"];
      if (dest != null) {
        List<LatLng> points = [];
        var pt1 = LatLng(toDouble(element["lat"]), toDouble(element["lng"]));
        var pt2 = LatLng(toDouble(dest["lat"]), toDouble(dest["lng"]));
        var distance = AMapTools.distanceBetween(pt1, pt2);
        if (distance > 5) {
          points.add(pt1);
          points.add(pt2);
          final Polyline polyline = Polyline(
              width: 20,
              joinType: JoinType.round,
              capType: CapType.round,
              geodesic: true,
              customTexture:
                  BitmapDescriptor.fromIconPath(R.image_poi_texture_line),
              points: points);
          tmpPolylines["c_${element["id"]}"] = polyline;
        }
      }
    }
    _polylines.clear();
    _polylines.addAll(tmpPolylines);
  }

  /// 渲染车辆
  calcCluster() {
    Map<String, Marker> tmpMarkers = {};
    var clusterKit = ClusterKit();
    clusterKit.calcPoints(_data["car_list"], _curZoom);
    var cluseterList = clusterKit.getData();
    for (var element in cluseterList) {
      BitmapDescriptor icon;
      if (element.pts.length == 1) {
        var status = element.pts[0]["status"];
        var carNo = element.pts[0]["car_no"];
        icon = BitmapDescriptor.fromIconPath(status == 3
            ? (carNo == _car_no ? R.image_poi_car3_3 : R.image_poi_car3)
            : status == 4
                ? (carNo == _car_no ? R.image_poi_car4_4 : R.image_poi_car4)
                : status == 2
                    ? (carNo == _car_no ? R.image_poi_car2_2 : R.image_poi_car2)
                    : status == -1
                        ? (carNo == _car_no
                            ? R.image_poi_car1_1
                            : R.image_poi_car1)
                        : R.image_poi_car2);
      } else {
        icon = BitmapDescriptor.fromIconPath(getMarkerIcon(element.pts.length));
      }
      var marker = Marker(
        zIndex: 1,
        position: element.center,
        icon: icon,
        infoWindowEnable: false,
        onTap: (e) {
          _popCarClick(element);
        },
      );
      tmpMarkers["m_" + marker.id] = marker;
    }
    setState(() {
      _markers.removeWhere((key, value) {
        return key.startsWith("m_");
      });
      _markers.addAll(tmpMarkers);
    });
  }

  /// 用数字图标来标记多辆车辆
  String getMarkerIcon(int num) {
    if (num == 1) {
      return R.image_poi_car;
    } else if (num == 2) {
      return R.image_poi_m2;
    } else if (num == 3) {
      return R.image_poi_m3;
    } else if (num == 4) {
      return R.image_poi_m4;
    } else if (num == 5) {
      return R.image_poi_m5;
    } else if (num == 6) {
      return R.image_poi_m6;
    } else if (num == 7) {
      return R.image_poi_m7;
    } else if (num == 8) {
      return R.image_poi_m8;
    } else if (num == 9) {
      return R.image_poi_m9;
    } else {
      return R.image_poi_m9_;
    }
  }

  /// 点击站点
  _popStationClick(element) {
    print("站点");
    StationModel station = StationModel.fromMap(element);
    if (_isShowPopSelectCar) {
      //选车调车
      ClickStationsEvent event = ClickStationsEvent(station);
      eventBus.fire(event);
    } else {
      //选点调车
      OpenUtils.pop4(context, PopStations(station), Colors.transparent);
    }
    // 站点选中效果
    currenActiveStation = element;
    renderStation2();
  }

  /// 点击车辆
  _popCarClick(Cluster element) {
    _selectElement = element;
    List list = [];
    element.pts.forEach((item) {
      var latlng1 = LatLng(
          toDouble(element.pts[0]["lat"]), toDouble(element.pts[0]["lng"]));
      var latlng2 = LatLng(toDouble(item["lat"]), toDouble(item["lng"]));
      if (item["id"] != element.pts[0]["id"]) {
        var distance = AMapTools.distanceBetween(latlng1, latlng2);
        item["c_distance"] = distance;
      } else {
        item["c_distance"] = 0;
      }
      list.add(item);
    });
    list.sort((item1, item2) {
      return (item1["c_distance"] * 100 - item2["c_distance"] * 100).toInt();
    });
    OpenUtils.popCars(context, list, PopEnterType.map);
    _car_no = element.pts[0]["car_no"];
    calcCluster();
  }

  Widget _renderContent(dynamic data) {
    if (_status == -1 || _status == 2 || _status == 3 || _status == 4) {
      List list = [];
      List carList = List.from(_data["car_list"]);
      for (var item in carList) {
        if (_isAll ||
            item["status"] == 4 && _isDidpatch ||
            item["status"] == 3 && _isWork ||
            item["status"] == 2 && _isWait ||
            item["status"] == -1 && _isBroke) {
          list.add(item);
        }
      }
      _temporaryData = _data;
      _temporaryData["car_list"] = list;
      _data = _temporaryData;
    }
    var size = MediaQuery.of(context).size;
    return SizedBox(
      width: size.width,
      height: size.height,
      child: Stack(
        children: [
          _renderMap(),
          Column(
            children: [
              50.hspace,
              _renderCarCard(),
              // 6.hspace,
              _renderResetLoc(),
              const Spacer(),
              _renderBottom(),
            ],
          )
        ],
      ),
    );
  }

  /// 初始化地图
  Widget _renderMap() {
    var pt = _data["center_info"];
    return AMapWidget(
      apiKey: const AMapApiKey(
          androidKey: Config.androidAmapKey, iosKey: Config.iOSAmapKey),
      onMapCreated: _onMapCreated,
      privacyStatement: const AMapPrivacyStatement(
          hasContains: true, hasShow: true, hasAgree: true),
      //initialCameraPosition: CameraPosition(target: LatLng(22.560857, 114.039319)),
      initialCameraPosition: CameraPosition(
          target: LatLng(toDouble(pt["lat"]), toDouble(pt["lng"]))),
      markers: Set<Marker>.of(_markers.values),
      polylines: Set<Polyline>.of(_polylines.values),
      buildingsEnabled: false,
      labelsEnabled: false,
      onCameraMove: (position) {
        Log.i(position.toString());
        var delt = position.zoom - _curZoom;
        if (delt > 0.5 || delt < -0.5) {
          _curZoom = position.zoom;
          calcCluster();
        }
      },
    );
  }

  /// 我的位置
  Widget _renderResetLoc() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        GestureDetector(
          onTap: () {
            setState(() {
              _isLoading = true;
              _status = 0;
              _isAll = true;
              _isWork = false;
              _isWait = false;
              _isDidpatch = false;
              _isBroke = false;
              _car_no = "";
            });
            _stateLayoutController.reload();
            _moveToPosition();
            /// 清空站点选中图钉
            renderStation3();
          },
          child: Card(
            child: SizedBox(
              width: 44.rpx,
              height: 44.rpx,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  _isLoading
                      ? SizedBox(
                          width: 20.rpx,
                          height: 20.rpx,
                          child: CircularProgressIndicator(
                            strokeWidth: 2.rpx,
                            color: UIColor.color_t3,
                          ))
                      : Icon(Icons.my_location_sharp,
                          size: 24.rpx, color: const Color(0xff54BD95)),
                ],
              ),
            ),
          ),
        ),
        5.wspace,
      ],
    );
  }

  /// 车辆列表
  Widget _renderCarCard() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        GestureDetector(
          onTap: () {
            OpenUtils.pop2(context, PopCarList(null));
          },
          child: Card(
            child: SizedBox(
              width: 44.rpx,
              height: 68.rpx,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  SvgPicture.asset(R.image_car_list,
                      width: 24.rpx, height: 24.rpx),
                  4.hspace,
                  UText.get("列表", Colors.black.withOpacity(0.6), 12.rpx),
                ],
              ),
            ),
          ),
        ),
        5.wspace,
      ],
    );
  }

  /// 车辆状态选栏
  Widget _renderBottom() {
    var st = _data["satistics_info"];
    return ClipRect(
      child: BackdropFilter(
        filter: ImageFilter.blur(sigmaX: 2.rpx, sigmaY: 2.rpx),
        child: Container(
          width: double.infinity,
          height: 76.rpx,
          margin: EdgeInsets.only(left: 10.rpx, right: 10.rpx, bottom: 30.rpx),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10.rpx)),
            boxShadow: [
              BoxShadow(
                color: UIColor.color_shadow2,
                offset: const Offset(0, 2), //阴影y轴偏移量
                blurRadius: 4, //阴影模糊程度
                // spreadRadius: 0 //阴影扩散程度
              )
            ],
          ),
          child: Row(
            children: [
              8.wspace,
              _renderCarStatus("全部", 0, UIColor.color_primary, all_count),
              8.wspace,
              _renderCarStatus(
                  "任务中", 3, UIColor.color_primary, st["work_count"]),
              8.wspace,
              _renderCarStatus(
                  "空闲中", 2, UIColor.color_primary, st["unemployed_count"]),
              8.wspace,
              _renderCarStatus(
                  "调配中", 4, UIColor.color_primary, st["dispatch_count"]),
              8.wspace,
              _renderCarStatus(
                  "不可用", -1, UIColor.color_primary, st["charge_count"]),
              8.wspace,
            ],
          ),
        ),
      ),
    );
  }

  /// 渲染车辆状态栏每一项
  Widget _renderCarStatus(String name, int status, Color color, int count) {
    return Expanded(
      child: GestureDetector(
        onTap: () async {
          _isAll = false;
          _isWork = false;
          _isDidpatch = false;
          _isWait = false;
          _isBroke = false;
          if (status == 0) {
            _isAll = true;
          } else if (status == 4) {
            _isDidpatch = true;
          } else if (status == 3) {
            _isWork = true;
          } else if (status == 2) {
            _isWait = true;
          } else if (status == -1) {
            _isBroke = true;
          }
          List list = [];
          var _sp = await SharedPreferences.getInstance();
          _datCache = jsonDecode(_sp.getString("dataCache") ?? "");
          List carList = List.from(_datCache["car_list"]);
          for (var item in carList) {
            if (_isAll ||
                item["status"] == 4 && _isDidpatch ||
                item["status"] == 3 && _isWork ||
                item["status"] == 2 && _isWait ||
                item["status"] == -1 && _isBroke) {
              list.add(item);
            }
          }
          _temporaryData = _datCache;
          _temporaryData["car_list"] = list;
          _temporaryData["satistics_info"] = _data["satistics_info"];
          _status = status;
          _onDataCallback(_temporaryData);
          _datCache["car_list"] = carList;
          _sp.setString("dataCache", jsonEncode(_datCache));
        },
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8.rpx),
            border: Border.all(
                color: status == 0 && _isAll ||
                        status == 3 && _isWork ||
                        status == 2 && _isWait ||
                        status == 4 && _isDidpatch ||
                        status == -1 && _isBroke
                    ? UIColor.color_primary
                    : const Color(0xFFD2E0EE),
                width: 1.rpx),
            color: status == 0 && _isAll ||
                    status == 3 && _isWork ||
                    status == 2 && _isWait ||
                    status == 4 && _isDidpatch ||
                    status == -1 && _isBroke
                ? UIColor.color_primary
                : Colors.white,
          ),
          child: SizedBox(
            height: 56.rpx,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    UText.get(
                        name,
                        status == 0 && _isAll ||
                                status == 3 && _isWork ||
                                status == 2 && _isWait ||
                                status == 4 && _isDidpatch ||
                                status == -1 && _isBroke
                            ? Colors.white
                            : UIColor.color_t8,
                        12.rpx),
                    3.hspace,
                    UText.get(
                        "$count",
                        status == 0 && _isAll ||
                                status == 3 && _isWork ||
                                status == 2 && _isWait ||
                                status == 4 && _isDidpatch ||
                                status == -1 && _isBroke
                            ? Colors.white
                            : color,
                        20.rpx,
                        fw: FontWeight.w600),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  _onMapCreated(AMapController controller) {
    setState(() {
      _mapController = controller;
      _moveToPosition();
    });
  }

  _moveToPosition() {
    var pt = _data["center_info"];
    _mapController?.moveCamera(
      CameraUpdate.newCameraPosition(
        CameraPosition(
            target: LatLng(toDouble(pt["lat"]), toDouble(pt["lng"])),
            zoom: 16,
            tilt: 0,
            bearing: 0),
      ),
      animated: true,
    );
  }

  @override
  void setState(fn) {
    //重写setState，加一个安全判断，Widget是否安装在tree上
    if (mounted) {
      super.setState(fn);
    }
  }
}
